﻿using EC18_ESHOP.Filters;
using EC18_ESHOP.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;
using System.Net.Mail;
using EC18_ESHOP.Content.Filters;

namespace EC18_ESHOP.Controllers
{
    [Authorize(Roles="Customer")]
    public class CartController : Controller
    {
        EShopEntities db = new EShopEntities();

        //
        // GET: /Cart/
        [NoCacheAttribute]//disable cache, sử dụng để tránh trường hợp nhấn back trên trình duyệt để trở lại trang này mà không gọi lại các hàm jquery trên view
        public ActionResult Index()
        {
            CART cart = db.CART.Where(c => c.UserId == WebSecurity.CurrentUserId).FirstOrDefault();
            return View(cart);
        }


        public ActionResult getSaleOff(int id)
        {
            var list = new List<object>();
            var saleoff = db.SALEOFF.Where(s => s.EndDate.CompareTo(DateTime.Now) > 0).ToList();
            foreach (var item in saleoff)
            {
                var detail = item.SALEOFF_DETAIL.Where(s => s.ProductId == id).FirstOrDefault();
                if (detail != null)
                {
                    var productsale = new { SaleOffName = item.SaleOffName, Discount = detail.Discount };
                    list.Add(productsale);
                }
            }
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        
        public ActionResult PurchaseSuccess()
        {
            CART cart = db.CART.Where(c => c.UserId == WebSecurity.CurrentUserId).FirstOrDefault();
            if (cart != null)
            {
                UserProfile user = db.UserProfile.Find(WebSecurity.CurrentUserId);
                if (user != null)
                {
                    string email = user.Email;
                    string subject = "Hệ thống TMĐT Eshop - Thông tin mua hàng";

                    string message = String.Format("Danh sách các món hàng mà bạn đã mua vào ngày <strong>{0}</strong>: <br/>", DateTime.Now.ToShortDateString());

                    var detaillist = cart.CART_DETAIL.ToList();//copy sang một list khac' để delete
                    foreach (var detail in detaillist)
                    {
                        message += String.Format("+ <strong>Tên sản phẩm:</strong> {0} - <strong>Giá:</strong> {1} - <strong>Số lượng:</strong> {2}<br/>", detail.PRODUCT.ProductName, detail.PRODUCT.ProductPrice, detail.Quantity);
                        db.CART_DETAIL.Remove(detail);
                    }
                    doSendmail(message, email, subject);
                }

                
                db.CART.Remove(cart);
                try
                {
                    db.SaveChanges();
                }
                catch
                {
                    return View();
                }
            }
            return View();
        }

        private void doSendmail(string message, string emailTo, string subject)
        {
            try
            {
                MailMessage mail = new MailMessage();
                mail.To.Add(new MailAddress(emailTo));
                mail.Subject = subject;
                mail.Body = message;
                mail.IsBodyHtml = true;

                SmtpClient smtp = new SmtpClient();
                smtp.EnableSsl = true;
                smtp.Send(mail);
            }
            catch
            {

            }
        }


        public ActionResult removeItem(int id)
        {
            CART cart = db.CART.Where(c => c.UserId == WebSecurity.CurrentUserId).FirstOrDefault();
            if (cart != null)
            {
                var cartdetail = cart.CART_DETAIL.Where(cd => cd.ProductId == id).FirstOrDefault();
                if (cartdetail != null)
                {
                    db.CART_DETAIL.Remove(cartdetail);
                    try
                    {
                        db.SaveChanges();
                    }
                    catch
                    {
                        return RedirectToAction("Index");
                    }
                }
            }
            return RedirectToAction("Index");
        }

        //
        // POST: /Cart/addToCart
        public ActionResult addToCart(int ProductId)
        {
            try
            {
                int UserId = WebSecurity.GetUserId(User.Identity.Name);
                if (UserId != -1)
                {
                    CART cart = db.CART.Where(p => p.UserId == UserId).First();
                    List<CART_DETAIL> arrCartDetail = cart.CART_DETAIL.ToList();
                    int count = arrCartDetail.Count();
                    bool isAvail = false;
                    int quantity = 0;
                    int indexAvail = 0;
                    for (int i = 0; i < count; i++)
                    {
                        if (arrCartDetail[i].ProductId == ProductId)
                        {
                            isAvail = true;
                            indexAvail = arrCartDetail[i].CardDetailId;
                            quantity = arrCartDetail[i].Quantity + 1;
                            break;
                        }
                    }
                    if (!isAvail)
                    {
                        CART_DETAIL cart_detail = new CART_DETAIL();
                        cart_detail.ProductId = ProductId;
                        cart_detail.CART = cart;
                        cart_detail.Quantity = 1;

                        db.CART_DETAIL.Add(cart_detail);
                        if (cart.QuantityOfProduct == 0)
                        {
                            cart.FirstDateAdd = DateTime.Now;
                        }
                        cart.QuantityOfProduct = cart.QuantityOfProduct + 1;
                    }
                    else
                    {
                        CART_DETAIL cart_detail = db.CART_DETAIL.Find(indexAvail);
                        cart_detail.Quantity++;
                    }
                    db.SaveChanges();
                }
                //return Json(new { status = true }, JsonRequestBehavior.AllowGet);
                return RedirectToAction("Index", "Cart");
            }
            catch (Exception ex)
            {
                return RedirectToAction("Index", "Home");
            }
        }

        //
        // POST: /Cart/addToWishList
        public ActionResult addToWishList(int productId)
        {
            try
            {
                int userId = WebSecurity.GetUserId(User.Identity.Name);
                if (userId != -1)
                {
                    UserProfile profile = db.UserProfile.Find(userId);
                    PRODUCT product = db.PRODUCT.Find(productId);
                    if (!product.UserProfile2.Contains(profile))
                    {
                        product.UserProfile2.Add(profile);
                        db.SaveChanges();
                    }
                }
                return Redirect(Request.UrlReferrer.ToString());
            }
            catch (Exception ex)
            {
                return Redirect(Request.UrlReferrer.ToString());
            }
        }

        //
        // POST: /Cart/addToRecentlyView
        public void addToRecentlyView(int productId)
        {
            try
            {
                int userId = WebSecurity.GetUserId(User.Identity.Name);
                if (userId != -1)
                {
                    UserProfile profile = db.UserProfile.Find(userId);

                    PRODUCT product = db.PRODUCT.Find(productId);
                    if (!product.UserProfile1.Contains(profile))
                    {
                        int maxQuantity = int.Parse(db.PARAMETER.Where(p => p.ParameterName == "quantityRecenly").First().Value);
                        if (profile.PRODUCT1.Count >= maxQuantity)
                        {
                            List<PRODUCT> arrProduct = profile.PRODUCT1.ToList();
                            profile.PRODUCT1.Remove(arrProduct[0]);
                        }
                        product.UserProfile1.Add(profile);
                    }
                }
                db.SaveChanges();
            }
            catch (Exception ex) { }
        }
    }
}
